import { classicBeh } from '../classic-beh.js';

const mMgr = wx.getBackgroundAudioManager();

Component({
  /**
   * 组件的属性列表
   */
  behaviors: [classicBeh],

  properties: {
    src: String,
    title: String
  },

  /**
   * 组件的初始数据
   */
  data: {
    playing: false,
    pauseSrc: 'images/player@pause.png',
    playSrc: 'images/player@play.png'
  },

  attached: function(event) {
    this._recoverStatus();
    this._monitorSwitch();
  },

  detached: function(event) {
    // mMgr.stop();
  },

  /**
   * 组件的方法列表
   */
  methods: {
    onPlay: function(event) {
      if(!this.data.playing) {
        // 图片切换成暂停
        this.setData({
          playing: true
        })
        mMgr.src = this.properties.src;
      }else {
        // 图片切换成播放
        this.setData({
          playing: false
        })
        mMgr.pause();
      }
      mMgr.title = this.properties.title;
    },
    
    // 解决页面切换，页面音乐开关不一致的问题
    _recoverStatus: function () {
      if(mMgr.paused) {
        this.setData({
          playing: false
        })
        return
      }
      if(mMgr.src == this.properties.src) {
        this.setData({
          playing: true
        })
      }
    },
    
    // 解决音乐总控开关和页面音乐开关不一致的问题
    _monitorSwitch: function () {
      mMgr.onPlay(() => {
        this._recoverStatus()
      })
      mMgr.onPause(() => {
        this._recoverStatus()
      })
      mMgr.onStop(() => {
        this._recoverStatus()
      }),
      mMgr.onEnded(() => {
        this._recoverStatus()
      })
    }
  }
})
